package com.candy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        将请求和响应对象进行转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
//        获取session对象
        HttpSession session=req.getSession(false);
//        判断用户是否登录，将登录的状态保存起来
        boolean logined=(session!=null&&session.getAttribute("user")!=null );
//        获取请求的来源
        String requetUrl=req.getRequestURI();
//        判断，若用户是没有进行登录的状态，且请求的来源是不是登录的界面
        if(!logined && !requetUrl.endsWith("/index.jsp") && !requetUrl.endsWith("/login")){
//            将页面重定向到登录的界面
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录过滤器的初始化方法");
    }

    @Override
    public void destroy() {
        System.out.println("登录过滤器的销毁方法");
    }
}
